package com.example.liuhu;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSONObject;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class ExController {

    @Autowired
    Executor asyncLocalStorageExecutor;
    final int totalTasks = 16;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    public void upload(@RequestParam(value = "company", required = true) MultipartFile company, @RequestParam(value = "record", required = true) MultipartFile record,HttpServletResponse response) throws Exception {


        ImportParams params = new ImportParams();

        params.setHeadRows(1);
        params.setNeedSave(true);
        params.setVerifyFileSplit(false);


        ExcelImportResult<Company> companyResult = ExcelImportUtil.importExcelMore(company.getInputStream(), Company.class, params);
        ExcelImportResult<Record> recordResult = ExcelImportUtil.importExcelMore(record.getInputStream(), Record.class, params);
        List<Company> companyList = companyResult.getList().stream().filter(x->x.getName()!=null).collect(Collectors.toList());
        List<Record> recordList = recordResult.getList();

        System.out.println("-----");
        List<List<Record>> partition = Lists.partition(recordList, totalTasks);
        System.out.println("-----");

        CopyOnWriteArrayList<CopyOnWriteArrayList<Result>> nn = new CopyOnWriteArrayList<>();
        for (Company s : companyList) {
            String name = s.getName().trim().replaceAll("\n", "");
            s.setName(name);

            CopyOnWriteArrayList<Result> mm = new CopyOnWriteArrayList<>();

            CountDownLatch countDownLatch = new CountDownLatch(partition.size());
            for (int i = 0; i < partition.size(); i++) {
                int finalI = i;
                asyncLocalStorageExecutor.execute(new Runnable() {
                    public void run() {
                        try {
                            List<Record> strings = partition.get(finalI);
                            for (Record re : strings) {
                                String content = re.content;
                                String name = s.getName();
                                if (content != null&&content.length() > 0) {
                                    if (content.contains(name)) {
                                        Result result = new Result();
                                        result.setCompanyName(s.getName());
                                            if (re.getDate()!=null){
                                                result.setDate(re.getDate());
                                                result.setContent(re.getContent());
                                                mm.add(result);
                                            }
                                    }
                                }
                            }
                            System.out.println(countDownLatch.getCount());
                            countDownLatch.countDown();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            try {

                countDownLatch.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mm.size()==0) {
                Result build = Result.builder()
                        .companyName(s.getName())
                        .build();
                mm.add(build);
            }
            nn.add(mm);



        }

        for (CopyOnWriteArrayList<Result> results : nn) {
            System.out.println(results);
        }
        List<Result> exportList = nn.stream().map(x -> {
            if (x.size()==1) {
                return x.get(0);
            }else{
                Result res = null;
                for (Result result : x) {
                    if (res!=null&&res.getDate()!=null&&result.getDate()!=null){
                        if (res.getDate().before(result.getDate())){
                            res = result;
                        }
                    }else{
                        res = result;
                    }

                }
                return res;
            }

        }).collect(Collectors.toList());


        ExcelUtils.exportExcel(exportList, null, "导出sheet1", Result.class, "测试user.xlsx", response);


    }

}
